//
// Created by amon.huang on 2021/7/25.
//

#include "PushJNICall.h"
#include "PushConstDefine.h"

PushJNICall::PushJNICall(JavaVM *javaVm, JNIEnv *jniEnv, jobject jPushObj) {
    this->javaVM = javaVm;
    this->jniEnv = jniEnv;
    this->jPushObj = jniEnv->NewGlobalRef(jPushObj);

    jclass jPushClazz = jniEnv->GetObjectClass(jPushObj);
    this->jConnectErrorMid = jniEnv->GetMethodID(jPushClazz, "onConnectError", "(ILjava/lang/String;)V");
    this->jConnectSuccessMid = jniEnv->GetMethodID(jPushClazz, "onConnectSuccess", "()V");
}

PushJNICall::~PushJNICall() {
    jniEnv->DeleteGlobalRef(jPushObj);
}

void PushJNICall::onConnectError(PushThreadMode threadMode, int errorCode, char *msg) const {
    if (threadMode == PUSH_THREAD_MAIN) {
        jstring javaMsg = jniEnv->NewStringUTF(msg);
        jniEnv->CallVoidMethod(jPushObj, jConnectErrorMid);
        jniEnv->DeleteLocalRef(javaMsg);
    } else if (threadMode == PUSH_THREAD_CHILD) {
        JNIEnv *env;
        if (javaVM->AttachCurrentThread(&env, nullptr) != JNI_OK) {
            LOGE("javaVM attach current thread error");
        }
        jstring javaMsg = env->NewStringUTF(msg);
        env->CallVoidMethod(jPushObj, jConnectErrorMid, errorCode, javaMsg);
        env->DeleteLocalRef(javaMsg);
        javaVM->DetachCurrentThread();
    }
}

void PushJNICall::onConnectSuccess(PushThreadMode threadMode) const {
    if (threadMode == PUSH_THREAD_MAIN) {
        jniEnv->CallVoidMethod(jPushObj, jConnectSuccessMid);
    } else if (threadMode == PUSH_THREAD_CHILD) {
        JNIEnv *env;
        if (javaVM->AttachCurrentThread(&env, nullptr) != JNI_OK) {
            LOGE("javaVM attach current thread error");
        }
        env->CallVoidMethod(jPushObj, jConnectSuccessMid);
        javaVM->DetachCurrentThread();
    }
}
